package com.wyth.lottery.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.wyth.lottery.R;
import com.wyth.lottery.activity.SSQSelectActivity;
import com.wyth.lottery.activity.ShoppingActivity;
import com.wyth.lottery.base.BaseFragment;
import com.wyth.lottery.base.SaveUtils;
import com.wyth.lottery.bean.RandomBean;
import com.wyth.lottery.bean.SSQDataBZBean;
import com.wyth.lottery.bean.SSQDataBean;
import com.wyth.lottery.bean.SSQSelectBean;
import com.wyth.lottery.service.Entity.Detail;
import com.wyth.lottery.service.presenter.DetailPresenter;
import com.wyth.lottery.service.view.DetailView;
import com.wyth.lottery.utils.BuildParamUtils;
import com.wyth.lottery.utils.MathC;
import com.wyth.lottery.utils.MyApplication;
import com.wyth.lottery.utils.Number;
import com.wyth.lottery.utils.RandomUtils;
import com.wyth.lottery.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by phh on 2017/10/31.
 * 双色球标准界面
 */

public class BZFragment extends BaseFragment {
    private DetailPresenter mDetailPresenter;
    private String detailInfo;


    Handler mHandler = new Handler();

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mDetailPresenter.getDetail(detailInfo);
        }
    };
    @BindView(R.id.rv_red)
    RecyclerView mRvRed;
    @BindView(R.id.rv_blue)
    RecyclerView mRvBlue;
    @BindView(R.id.tv_red_number)
    TextView mTvRedNumber;
    @BindView(R.id.tv_blue_number)
    TextView mTvBlueNumber;
    @BindView(R.id.tv_number_bei)
    TextView mTvNumberBei;
    @BindView(R.id.tv_money_number)
    TextView mTvMoneyNumber;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.bonus_status)
    TextView mBonusStatus;
    @BindView(R.id.duplex_time)
    TextView mDuplexTime;

    private int RedNumber = 0;
    private int BlueNumber = 0;

    private int sign = 0;

    private ArrayList<SSQSelectBean> red = new ArrayList<>();
    private ArrayList<SSQSelectBean> blue = new ArrayList<>();
    private BlueAdapter mBlueAdapter;
    private RedAdapter mRedAdapter;
    private List<SSQSelectBean> mMred;
    private List<SSQSelectBean> mMblue;
    private int mNumber;
    private int number;//这是注数
    //TODO 这是服务器获取的限制钱数数据,需要赋值
    private int mGetMaxMoney;

    @Override
    protected View getSuccessView() {
        View view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.fragment_ssq_bz, null);
        return view;
    }

    /**
     * 当用户在购物车列表中点击标准条目中的修改后,回到这里
     *
     * @param event
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object event) {
        if (event instanceof SSQDataBZBean) {
            sign = 1;
            mMred = ((SSQDataBZBean) event).getRed();
            mMblue = ((SSQDataBZBean) event).getMblue();
            for (SSQSelectBean ssqSelectBean : mMred) {
                String text = ssqSelectBean.getText();
                if (red != null) {
                    for (SSQSelectBean selectBean : red) {
                        if (text.equals(selectBean.getText())) {
                            selectBean.selectBoolean = false;
                        }
                    }
                }

            }
            for (SSQSelectBean ssqSelectBean : mMblue) {
                String text = ssqSelectBean.getText();
                for (SSQSelectBean selectBean : blue) {
                    if (text.equals(selectBean.getText())) {
                        selectBean.selectBoolean = false;
                    }
                }
            }
            RedNumber = mMred.size();
            BlueNumber = mMblue.size();
            mTvRedNumber.setText(String.valueOf(RedNumber));
            mTvBlueNumber.setText(String.valueOf(BlueNumber));
            int money = ((SSQDataBZBean) event).getMoney();
            mNumber = MathC.number(RedNumber, BlueNumber);
            int i = money / 2 / mNumber;
            mTvNumberBei.setText(String.valueOf(i));
            mBlueAdapter.setNewData(blue);
            mRedAdapter.setNewData(red);
            setText();
        }
    }

    @Override
    protected void initDate() {
        stateLayout.showSuccessView();
        initBlueRV();
        initRedRV();
        EventBus.getDefault().register(this);

        SSQDataBZBean stickyEvent = EventBus.getDefault().getStickyEvent(SSQDataBZBean.class);
        if (stickyEvent != null) {
            EventBus.getDefault().removeStickyEvent(stickyEvent);
        }
        mBonusStatus.setText(SaveUtils.getGoodsInfos().mBonusStatus);
        mDuplexTime.setText(SaveUtils.getGoodsInfos().mDuplexTime);

        initData();
    }

    private void initData() {
        mDetailPresenter = new DetailPresenter(MyApplication.getContext());
        Gson gson = new Gson();
        Map<String, String> param = new HashMap<String, String>();
        param.put("sid", "yhl");
        param.put("cmd", "3301");
        param.put("platform", "andorid");
        param.put("sysVer", "android4.2");
        param.put("softVer", "v1.0");
        param.put("width", "800");
        param.put("height", "1024");
        param.put("machId", "aaaaa");
        param.put("func", "cur");


        String msgs = "{\"lotteryId\":\"001\"}";
        param.put("msg", msgs);
        String currMd5 = BuildParamUtils.buildMd5(param, "yhlkey");
        param.put("md5", currMd5);
        detailInfo = gson.toJson(param);

        mHandler.post(mRunnable);
        mDetailPresenter.onCreate();
        mDetailPresenter.attachView(mBookVieww);
    }

    public com.wyth.lottery.service.Entity.SSQSelectBean.IssueListBean.IssueBean mIssueBean;
    private DetailView mBookVieww = new DetailView() {

        @Override
        public void onSuccess(Detail detail) {
            System.out.println(detail+"---------------------------------------");
            Gson gson = new Gson();
            com.wyth.lottery.service.Entity.SSQSelectBean ssqSelectBean = gson.fromJson(detail.getResult(), com.wyth.lottery.service.Entity.SSQSelectBean.class);
            List<com.wyth.lottery.service.Entity.SSQSelectBean.IssueListBean> issueList = ssqSelectBean.getIssueList();
            com.wyth.lottery.service.Entity.SSQSelectBean.IssueListBean issueListBean = issueList.get(0);
            List<com.wyth.lottery.service.Entity.SSQSelectBean.IssueListBean.IssueBean> issue = issueListBean.getIssue();
            mIssueBean = issue.get(0);

            EventBus.getDefault().post(mIssueBean);
            SaveUtils.getGoodsInfos().mName = mIssueBean.getName();  //当前期次
            SaveUtils.getGoodsInfos().mBonusStatus = mIssueBean.getStartTime(); //官方开始时间
            SaveUtils.getGoodsInfos().mDuplexTime = mIssueBean.getDuplexTime(); //复试截止时间
            SaveUtils.getGoodsInfos().mSimplexTime = mIssueBean.getSimplexTime(); //单式截止时间
            mBonusStatus.setText(SaveUtils.getGoodsInfos().mBonusStatus);  //开始时间
            mDuplexTime.setText(SaveUtils.getGoodsInfos().mSimplexTime);

        }

        @Override
        public void onError(String result) {

        }
    };

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        mDetailPresenter.onStop();
        mHandler.removeCallbacks(mRunnable);
    }

    /**
     * 初始化蓝球
     */
    private void initBlueRV() {
        StaggeredGridLayoutManager staggeredGridLayoutManager1 = new StaggeredGridLayoutManager(7, StaggeredGridLayoutManager.VERTICAL);
        mRvBlue.setLayoutManager(staggeredGridLayoutManager1);
        Number.getList(16, blue);
        mBlueAdapter = new BlueAdapter(blue);
        mRvBlue.setAdapter(mBlueAdapter);
    }

    /**
     * 初始化红球
     */
    private void initRedRV() {
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(7, StaggeredGridLayoutManager.VERTICAL);
        mRvRed.setLayoutManager(staggeredGridLayoutManager);
        Number.getList(33, red);
        mRedAdapter = new RedAdapter(red);
        mRvRed.setAdapter(mRedAdapter);
    }

    @OnClick({R.id.jx_ten, R.id.jx_five, R.id.jx_one, R.id.iv_return, R.id.tv_next, R.id.zw_tv_bei, R.id.tv_number_bei, R.id.tv_mai})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.jx_ten:
                EventBus.getDefault().postSticky(new RandomBean(10, 1));
                startActivity(new Intent(MyApplication.getContext(), ShoppingActivity.class));
                getActivity().finish();
                break;
            case R.id.jx_five:
                EventBus.getDefault().postSticky(new RandomBean(5, 1));
                startActivity(new Intent(MyApplication.getContext(), ShoppingActivity.class));
                getActivity().finish();
                break;
            case R.id.jx_one:
                EventBus.getDefault().postSticky(new RandomBean(1, 1));
                startActivity(new Intent(MyApplication.getContext(), ShoppingActivity.class));
                getActivity().finish();
                break;
            case R.id.iv_return:
                if (sign == 0) {
                    getActivity().finish();
                } else if (sign == 1) {
                    //说明用户是从购物车点击修改进来的
                    //如果数据减少了,返回原来的数据
                    SaveUtils.getGoodsInfos().mlist.add(0, new SSQDataBean(mMred, mMblue, mNumber, "标准投注", mNumber * 2));
                    SaveUtils.getGoodsInfos().mTvMoney += (mNumber * 2);
                    SaveUtils.getGoodsInfos().mTvMoneyNumber += mNumber;
                    Intent intent = new Intent(MyApplication.getContext(), ShoppingActivity.class);
                    intent.putExtra("before", "before ");
                    startActivity(intent);
                }

                break;
            case R.id.tv_next:
                if (RedNumber < 6 || BlueNumber == 0) {
                    ToastUtil.makeToast("红球的个数不能小于6个,蓝球的个数不能等于0", 0);
//                    Toast.makeText(MyApplication.getContext(), "红球的个数不能小于6个,蓝球的个数不能等于0", Toast.LENGTH_SHORT).show();

                } else {
                    List<SSQSelectBean> mRed = new ArrayList<>();
                    List<SSQSelectBean> mblue = new ArrayList<>();
                    getNumber(mRed, mblue);
                    int number = MathC.number(RedNumber, BlueNumber);
                    int money = number * 2;
                    //测试1000
//                    mGetMaxMoney = 1000;
                    if (money >= mGetMaxMoney) {
                        ToastUtil.makeToast("单次投注不能超" + mGetMaxMoney, 0);
                        return;
                    }
                    EventBus.getDefault().postSticky(new SSQDataBean(mRed, mblue, number, 1, "标准投注", money));
                    startActivity(new Intent(MyApplication.getContext(), ShoppingActivity.class));
                    getActivity().finish();
                }
                break;

            case R.id.zw_tv_bei:
                initDialog();
                break;
            case R.id.tv_number_bei:
                initDialog();
                break;
            case R.id.tv_mai:
                initDialog();
                break;
        }
    }

    /**
     * 设置dalog
     */
    private void initDialog() {
        View view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.dalog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final AlertDialog alertDialog = builder.setView(view).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        WindowManager windowManager = getActivity().getWindowManager();
        Display defaultDisplay = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.height = (int) (defaultDisplay.getHeight() * 0.9);
        attributes.width = (int) (defaultDisplay.getWidth() * 0.6);
        window.setAttributes(attributes);


        final TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
        TextView tv_number1 = (TextView) view.findViewById(R.id.tv_number1);
        TextView tv_number2 = (TextView) view.findViewById(R.id.tv_number2);
        TextView tv_number3 = (TextView) view.findViewById(R.id.tv_number3);
        TextView tv_number4 = (TextView) view.findViewById(R.id.tv_number4);
        TextView tv_number5 = (TextView) view.findViewById(R.id.tv_number5);
        TextView tv_number6 = (TextView) view.findViewById(R.id.tv_number6);
        TextView tv_number7 = (TextView) view.findViewById(R.id.tv_number7);
        TextView tv_number8 = (TextView) view.findViewById(R.id.tv_number8);
        TextView tv_number9 = (TextView) view.findViewById(R.id.tv_number9);
        TextView tv_number0 = (TextView) view.findViewById(R.id.tv_number0);
        TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
        TextView tv_false = (TextView) view.findViewById(R.id.tv_false);
        TextView tv_true = (TextView) view.findViewById(R.id.tv_true);

        final List<String> mlist = new ArrayList<>();
        mlist.add("1");
        RandomUtils.SetOnClickListener(tv_number1, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number2, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number3, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number4, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number5, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number6, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number7, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number8, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number9, mlist, tv_number);
        RandomUtils.SetOnClickListener(tv_number0, mlist, tv_number);

        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mlist.size() != 0) {
                    mlist.remove(mlist.get(mlist.size() - 1));
                }
                StringBuffer stringBuffer = new StringBuffer();
                for (String s : mlist) {
                    stringBuffer.append(s);
                }
                tv_number.setText(stringBuffer.toString());
            }
        });

        tv_false.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        tv_true.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mlist.size() == 0) {
                    mlist.add(String.valueOf(1));
                    RandomUtils.getString(mlist, mTvNumberBei);
                    alertDialog.dismiss();
                } else {
                    RandomUtils.getString(mlist, mTvNumberBei);
                    alertDialog.dismiss();
                    setText();
                }
            }
        });

    }

    /**
     * 取出用户在标准界面选择的所有号码
     *
     * @param mRed
     * @param mBlue
     */
    private void getNumber(List<SSQSelectBean> mRed, List<SSQSelectBean> mBlue) {
        for (SSQSelectBean ssqSelectBean : red) {
            boolean selectBoolean = ssqSelectBean.selectBoolean;
            if (selectBoolean) {

            } else {
                mRed.add(new SSQSelectBean(ssqSelectBean.text, true, true));
            }
        }
        for (SSQSelectBean ssqSelectBean : blue) {
            boolean selectBoolean = ssqSelectBean.selectBoolean;
            if (selectBoolean) {
            } else {
                mBlue.add(new SSQSelectBean(ssqSelectBean.text, false, true));
            }
        }
    }


    /**
     * 红球的适配器
     */
    private class RedAdapter extends BaseQuickAdapter<SSQSelectBean, BaseViewHolder> {


        public RedAdapter(ArrayList<SSQSelectBean> data) {
            super(R.layout.ssq_red_item, data);
        }


        @Override
        protected void convert(final BaseViewHolder helper, final SSQSelectBean item) {
            final TextView textView = helper.getView(R.id.t);

            helper.setText(R.id.t, item.text);

            if (item.selectBoolean) {
                textView.setBackgroundResource(R.mipmap.img_red_false);
                textView.setTextColor(getResources().getColor(R.color.red));
            } else {
                textView.setBackgroundResource(R.mipmap.img_red_true);
                textView.setTextColor(getResources().getColor(R.color.white));

            }


            helper.setOnClickListener(R.id.t, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (item.selectBoolean) {
                        textView.setBackgroundResource(R.mipmap.img_red_true);
                        textView.setTextColor(getResources().getColor(R.color.white));
                        item.selectBoolean = false;
                        RedNumber++;
                        mTvRedNumber.setText(String.valueOf(RedNumber));
                        setText();
                    } else {
                        textView.setBackgroundResource(R.mipmap.img_red_false);
                        textView.setTextColor(getResources().getColor(R.color.red));
                        item.selectBoolean = true;
                        RedNumber--;
                        mTvRedNumber.setText(String.valueOf(RedNumber));
                        setText();
                    }

                }
            });
        }
    }

    /**
     * 蓝球的适配器
     */
    private class BlueAdapter extends BaseQuickAdapter<SSQSelectBean, BaseViewHolder> {


        public BlueAdapter(ArrayList<SSQSelectBean> item) {
            super(R.layout.ssq_blue_item, item);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final SSQSelectBean item) {
            final TextView textView = helper.getView(R.id.tt);

            helper.setText(R.id.tt, item.text);

            if (item.selectBoolean) {
                textView.setBackgroundResource(R.mipmap.img_blue_false);
                textView.setTextColor(getResources().getColor(R.color.ssqblue));
            } else {
                textView.setBackgroundResource(R.mipmap.img_blue_true);
                textView.setTextColor(getResources().getColor(R.color.white));
            }


            helper.setOnClickListener(R.id.tt, new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    if (item.selectBoolean) {
                        textView.setBackgroundResource(R.mipmap.img_blue_true);
                        textView.setTextColor(getResources().getColor(R.color.white));
                        item.selectBoolean = false;
                        BlueNumber++;
                        mTvBlueNumber.setText(String.valueOf(BlueNumber));
                        setText();

                    } else {
                        textView.setBackgroundResource(R.mipmap.img_blue_false);
                        textView.setTextColor(getResources().getColor(R.color.ssqblue));
                        item.selectBoolean = true;
                        BlueNumber--;
                        mTvBlueNumber.setText(String.valueOf(BlueNumber));
                        setText();
                    }

                }

            });


        }
    }

    private void setText() {
        number = MathC.number(RedNumber, BlueNumber);
        mTvMoneyNumber.setText(String.valueOf(number));
        mTvMoney.setText(String.valueOf(number * 2));
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mBonusStatus.setText(SaveUtils.getGoodsInfos().mBonusStatus);
            mDuplexTime.setText(SaveUtils.getGoodsInfos().mDuplexTime);
        }
    }
}
